import { Models } from '../../../../common/typings/model'
import Config from '../../../../config/Config'
import KoaRouter from 'koa-router'
import Mysql from '../../../../core/Mysql'
import { Success } from '../../../../core/HttpException'
import validator from '../../../../middlewares/validator'
import Auth from '../../../../middlewares/Auth'
import editRoleByid from '../../../../common/apiValidate/system/role/edit'
import RedisClient from '../../../../core/Redis'

const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/role`,
})

router.post('/edit', Auth.verifyTokenPermission, validator(editRoleByid, 'body'), async (ctx: Models.Ctx) => {
  const { id, name, parentId, describe, serialNum } = ctx.request.body
  await Mysql.command(`
    UPDATE
      role
    SET name = '${name}', parent_id = ${parentId}, \`describe\` = '${describe}', serial_num = ${serialNum}
    WHERE id = ${id}
  `)

  const scope = id
  Auth.getUserPermission({
    scope,
    uid: ctx.auth.uid,
  }).then((list) => {
    RedisClient.updateRoles(
      scope,
      new Map([
        ['id', id.toString()],
        ['parentId', parentId.toString()],
        ['permissions', list.map((item) => item.permission).join(',')],
      ])
    )
  })
  throw new Success()
})

export default router
